package cn.iotnc.camera.util

import android.content.Context
import android.view.View
import android.view.Window
import android.view.inputmethod.InputMethodManager
import org.jetbrains.anko.dip

/** Combination of all flags required to put activity into immersive mode */
const val FLAGS_FULLSCREEN =
    View.SYSTEM_UI_FLAG_LOW_PROFILE or
            View.SYSTEM_UI_FLAG_FULLSCREEN or
            View.SYSTEM_UI_FLAG_LAYOUT_STABLE or
            View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY or
            View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or
            View.SYSTEM_UI_FLAG_HIDE_NAVIGATION

const val FLAGS_HIDE_NAVIGATION =
    View.SYSTEM_UI_FLAG_LOW_PROFILE or
            View.SYSTEM_UI_FLAG_LAYOUT_STABLE or
            View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY or
            View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or
            View.SYSTEM_UI_FLAG_HIDE_NAVIGATION

fun Context.hideSoftInput(vararg views: View) {
    val inputMethodManager =
        getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    views.forEach {
        inputMethodManager.hideSoftInputFromWindow(it.windowToken, 0)
        it.clearFocus()
    }
}

/** makes visible a view. */
fun View.visible() {
    visibility = View.VISIBLE
}

/** makes gone a view. */
fun View.gone() {
    visibility = View.GONE
}

/** makes invisible a view. */
fun View.invisible() {
    visibility = View.INVISIBLE
}

fun Window.showOrHideSystemUi(show: Boolean) {
    if (show) {
        decorView.systemUiVisibility = (View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                or View.SYSTEM_UI_FLAG_IMMERSIVE)
    } else {
        decorView.systemUiVisibility = (View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hide nav bar
                or View.SYSTEM_UI_FLAG_FULLSCREEN // hide status bar
                or View.SYSTEM_UI_FLAG_IMMERSIVE
                or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY)
    }
}

fun View.setWindowInsets(topControl: View? = null, bottomControl: View? = null) {
    setOnApplyWindowInsetsListener { _, insets ->
        topControl?.setPadding(
            insets.systemWindowInsetLeft,
            insets.systemWindowInsetTop,
            insets.systemWindowInsetRight,
            0
        )
        bottomControl?.setPadding(
            insets.systemWindowInsetLeft + dip(8),
            dip(8),
            insets.systemWindowInsetRight + dip(8),
            insets.systemWindowInsetBottom + dip(8)
        )
        // clear this listener so insets aren't re-applied
        setOnApplyWindowInsetsListener(null)
        insets.consumeSystemWindowInsets()
    }
}